
import axios from "axios";
import { storage } from "../utils";
// import {user} from "../api/user"
// 这个是一个axios的实例 用于和后端交互时候，需要用户信息的时候（token）
const _axios = axios.create({
  baseURL: 'http://localhost:8080/api', // 设置基础URL
  headers: {
    'Content-Type': 'application/json', // 设置默认请求头
    'token': storage.get("token"), // 添加自定义请求头
  },
});

// 用户登录：
//      200（登录成功），415（账号或者密码错误），500（服务器错误）
async function userlogin(uname: string, uppassword: string): Promise<any> {
  try {
    const response = await axios.post("http://localhost:8080/api/login", {
      username: uname,
      password: uppassword,
    });
    return response.data.data.token;
  } catch (error: any) {
    if (error.code == "ERR_BAD_REQUEST") {
      return "415"
    } else {
      return "500"
    }
  }
}
// 用户自定义引擎更新：
async function updateUserEngines(userenginesList: { [key: string]: boolean }): Promise<any> {
  try {
    const formattedUserEnginesList: { [key: string]: boolean } = {};

    // 重新构造userenginesList对象
    Object.keys(userenginesList).sort().forEach((key: string) => {
      formattedUserEnginesList[key] = userenginesList[key];
    });

    const response = await _axios.post("/update-userengines", formattedUserEnginesList);
    return response.data.data;
  } catch (error) {
    return "401";
  }
}
// 用户注册
async function userenroll( myname: string, mypassword: string, myemail: string): Promise<any> {
  try {
    await axios.post("http://localhost:8080/api/enroll", {
        username: myname,
        userpassword: mypassword,
        usermail: myemail
    });

    return '201'
  } catch (error: any) {
    if (error.code == "ERR_BAD_REQUEST") {
      console.log(error);
      
      return "400"
    }
  }
}


//插入用户自定义tag
// const count = ref(0)
async function setUserTagIntoServer(Tags: any): Promise<any> {
  try {
    const responseuserId = await _axios.get("/block/getUserId")
    const response = await _axios.post("/block/inserter/" + responseuserId.data.data, Tags);
    return response.data
  } catch (error: any) {
    if (error.code == "ERR_BAD_REQUEST") {
      return "415"
    } else {
      return "500"
    }
  }
}

// 更新用户的需求搜索历史
async function updatechat_output(chatoutput: any): Promise<any> {
  try {
    const response = await _axios.post("/update-user-chatoutput", {
      "content": chatoutput
    })
    return response.data

  } catch (error) {

  }
}



// 根据tagid删除
async function deleteTagByTagId(tag_id: number) {
  const responce = await _axios.delete("/block/deleteTagByTagId", { params: { tag_id: tag_id } })
  return responce.data
}

// 修改用户密码
async function updataUserPassword(password:string) {
  try{
    const responce = await _axios.post("/update-userpassword",{userpassword:password})
    return responce.data
  }catch(error:any){
    return error.response.data.message;
  }
  
}

async function LoginTime(LoginTime:string) {
  console.log(LoginTime);
  try{
    const responce = await _axios.post("/login_Time",LoginTime);
    return responce;
  }catch{

  }
}

async function userhistoryLogin() {
  try{
    const responce = await _axios.post("/login_History")
    return responce.data.data;
  }catch{

  }
}

async function updatasaveSearch(keyword: string) {
  const data = {
    search: keyword
  };
  const response = await _axios.post("/user_search", data);
  return response;
}

async function deletesaveSearch() {
  const response = await _axios.post("/user_deletesearch");
  return response;
}




export { userlogin, userenroll, updateUserEngines, setUserTagIntoServer,
  deleteTagByTagId, updatechat_output,updataUserPassword,LoginTime,userhistoryLogin,updatasaveSearch,deletesaveSearch }

